namespace('base.menu');
/**
 * 初始化菜单设置页面
 */
base.menu.init = function(){
	var selectedMenuId = '';
	var menuType = $('#menuType').val();
	var menuTypeDescription = $('#menuTypeDescription').val();
	var setting = {
		async: {
			enable: true,
			url: 'base/menu/menu!fetchSubMenus.action',
			autoParam:['id'],
			otherParam: {'menuType': menuType}
		},
		data: {
			key: {
				checked: 'checked',
				url: 'xUrl' // modify the url key so to avoid going to the url page when be clicked;
			}
		},
		check: {
			enable: true
		},
		callback: {
			onClick: function(e, treeViewId, node){
				// 没有节点选中的情况下是selectedMenuId=''; 从而避免null被传到后台;
				selectedMenuId = node.id==null?'':node.id;
				if(selectedMenuId==''){
					// 根节点不可编辑;
					return;
				}
				$('#menuEditPanel').load('base/menu/menu!preUpdate.action?id=' + node.id, function(){
					base.menu.initMenuEditPanel();
				});
				return false;
			},
			onCheck: function(e, treeViewId, node){
				$.ajax('base/menu/menu!updateVisibility.action?menu.id=' + node.id + '&menu.visible=' + node.checked);
			},
			onAsyncError: function(event, treeId, treeNode, XMLHttpRequest, textStatus, errorThrown){
				// 需完善出错处理机制, 比如session timeout, permission denied;
				// 且需全局考虑类似session timeout而引起的ajax错误;
				alert('Error occurred while get sub menus');
			}
		}
	};

	// 构建一个静态的root节点,以方便全选/全反选,添加一级菜单等等;
	var root = [{
		id: null,
		name: menuTypeDescription,
		open: true,
		checked: true,
		isParent: true
	}];

	// 构建树;
	var zTree = $.fn.zTree.init($("#menuTreeView"), setting, root);
	
	// 获得并展开根节点;
	var rootNode = zTree.getNodes()[0];
	zTree.reAsyncChildNodes(rootNode, 'refresh', false);

	$('#btnAddMenu').click(function(){
		$('#menuEditPanel').load('base/menu/menu!preAdd.action?menuType=' + menuType + '&id=' + selectedMenuId, function(){
			base.menu.initMenuEditPanel();
		});
	});

	$('#btnDeleteMenu').click(function(){
		if(selectedMenuId==''){
			alert('您还没有选中任何节点');
			return;
		}
		$('#modalConfirmDeletemenu').modal({});
	});

	$('#btnConfirmDeleteMenu').click(function(){
		toLocation('base/menu/menu!delete.action?menuType=' + menuType + '&id=' + selectedMenuId);
	});
};
	
/**
 * 初始化菜单添加/编辑表单，使之ajaxForm
 */
base.menu.initMenuEditPanel = function(){
    $('.icon-gallery li').click(function(){
        var iconName = $(this).text();
        $('#menuStyleInputBox').val(iconName)
                .siblings('i').attr('class', 'add-on ' + iconName);
    });
    $('#menuEditForm').ajaxForm({
        target: '#menuEditPanel',
        success: function(){
            base.menu.reloadMenuTree();
            base.menu.initMenuEditPanel();
        }
    });
};

/**
 * 重新加载
 */
base.menu.reloadMenuTree = function(){
	var zTree = $.fn.zTree.getZTreeObj("menuTreeView");
	var rootNode = zTree.getNodes()[0];
	zTree.reAsyncChildNodes(rootNode, 'refresh', false);
};
